//
//  StringFunctionAvaliable.c
//  String
//
//  Created by Xavier on 2023/11/4.
//

#include "StringFunctionAvaliable.h"
/*
 需求分析：
 1、串的创建（采用顺序存储结构的动态分配存储表示）
 2、求串长
 3、两个串的比较
 4、清空串
 5、两个串的连接
 6、求子串
 7、求子串在主串的位置
 */

//串的创建
void HStringCreate(HString* Str, char* chars) {
    int chLength = 0;
    //求chars的长度
    while (chars[chLength] != '\0') {
        //char ch1 = chars[chLength];
        //char ch2 = chars[chLength+1];
        //printf("ch1:%c", chars[chLength]);
        //printf("ch2:%c", ch2);
        chLength++;
    }

    //开辟空间
    Str->ch = (char*)malloc(sizeof(char)*(chLength+1));//多开辟一个 0位置不用
    if (Str->ch == NULL) {
        printf("malloc is err!\n");
        exit(-1);
    }
    Str->length = chLength;
    
    //开始把chars里面的值给到Str 注意 str的0 是不用的
    int i = 1;
    for (i = 1; chars[i-1] != '\0'; i++) {
        Str->ch[i] = chars[i-1];
    }
    
}

//求串长
int HStringLength(HString* Str) {
    return Str->length;
}

//两个串的比较 - Str1>Str2 输出1 反之输出-1 相等输出0
int HStringCompare(HString* Str1, HString* Str2) {
    int i = 1;
    while ((i < Str1->length) || (i < Str2->length)) {
        if ((int)Str1->ch[i] > (int)Str2->ch[i]) {
            return 1;
        }else if((int)Str1->ch[i] < (int)Str2->ch[i]) {
            return -1;
        }else {
            i++;
        }
    }
    return 0;
}

//清空串
void HStringDestory(HString* Str) {
    free(Str->ch);
    Str->length = 0;
}

//两个串的连接
HString HStringConnection(HString* Str1, HString* Str2) {
    HString strRes;
    int strLength = HStringLength(Str1) + HStringLength(Str2) - 1;
    HStringCreate(&strRes, " ");
    strRes.length = strLength;
    int count = 1;
    for (count = 1; count <= Str1->length; count++) {
        strRes.ch[count] = Str1->ch[count];
    }
    for (int i = 1; i <= Str2->length; i++) {
        strRes.ch[count++] = Str2->ch[i];
    }
    return strRes;
}

//求子串
HString* GetSubstring(HString* Str, int Pos ,int Len) {
    HString* substring = NULL;
    HStringCreate(substring, " ");
    int i = Pos;
    int j = 1;
    for (int j = 1; j <= Len; j++) {
        substring->ch[j] = Str->ch[i++];
    }
    //printf("j:%d\n", j);
    //substring.ch[++j] = '\0';
    return substring;
}

//求子串在主串的位置
int GetSubstringIndexOfMainstring(HString* Mainstring, HString* Substring, int Pos) {
    int i = Pos;
    int j = 1;
    while (i <= Mainstring->length && j <= Substring->length) {
        if (Mainstring->ch[i] == Substring->ch[j]) {
            ++i;
            ++j;
        }else {
            i = i - j + 2;
            j = 1;
        }
    }
    if (j > Substring->length-1) {
        return i - Substring->length;
    }else {
        return 0;
    }
}

//串打印
void HStringPrint(HString* Str) {
    int i = 1;
    for (i = 1 ; Str->ch[i] != '\0'; i++) {
        printf("%c", Str->ch[i]);
    }
    printf("\n");
}

//void HStringPrint(HString* Str) {
//    int i = 1;
//    for (i = 1 ; i <= Str->length; i++) {
//        printf("%c", Str->ch[i]);
//    }
//    printf("\n");
//}



